#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : pythonProject1
@File : iptools.py
@Author : 蓝精灵
@Time : 2025/11/2 19:31  
@脚本说明 : 
"""
import ipaddress
import os
import concurrent.futures


# 辅助函数 网段扫描
def ip_segment(segment):
    ip_list = []
    try:
        if "/" in segment:
            # strict=False允许非网络地址开头
            ip_network = ipaddress.ip_network(segment, strict=False)
            # 获取网段内所有主机 (排除网络地址和广播地址)
            ip_list = [str(ip) for ip in ip_network.hosts()]
        elif "-" in segment:
            ip_start, ip_end = segment.replace(" ", "").split("-")
            # 转换为IP对象
            start = ipaddress.ip_address(ip_start)
            end = ipaddress.ip_address(ip_end)
            # 转换为整数后计算范围
            start_int = int(start)
            end_int = int(end)
            # 生成IP列表
            ip_list = [str(ipaddress.ip_address(i)) for i in range(start_int, end_int + 1)]
        else:
            exit()
        return ip_list
    except:
        exit()


def ip_scan(ip_host):
    result = os.popen(f"ping -n 1 -w 100 {ip_host}")
    if "TTL" in result.read().upper():
        print(f"[+] {ip_host} 存活")


def ip_scan_run(segment):
    if ip_segment(segment):
        with concurrent.futures.ThreadPoolExecutor(max_workers=10000) as executor:
            for host in ip_segment(segment):
                executor.submit(ip_scan, host)
    else:
        print("网段输入错误")